package org.jboss.netty.example.discardMine;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBufferFactory;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

public class DiscardServerHandler extends SimpleChannelHandler {

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
		// TODO Auto-generated method stub
		e.getCause().printStackTrace();
		Channel ch = e.getChannel();
		ch.close();
	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		// TODO Auto-generated method stub
		/*ChannelBuffer cb = (ChannelBuffer)e.getMessage();
		while(cb.readable()){
			System.out.print((char)cb.readByte());
			System.out.flush();
		}*/

		
		Channel channel = e.getChannel();
		channel.write(e.getMessage());
	}

	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("new connection");
		Channel ch = e.getChannel();
		String src = "5abcdefg";
		for(int i = 0 ; i <20 ; i++){
			ChannelFuture cf = ch.write(src);
			Thread.sleep(5000);
		}
		
		/*cf.addListener(new ChannelFutureListener() {		
			@Override
			public void operationComplete(ChannelFuture future) throws Exception {
				// TODO Auto-generated method stub
				Channel ch = future.getChannel();
				ch.close();
			}
		});*/
	}
}